import numpy as np
from python_ai.CV_5.single_respect.depth_separable_conv._csdn_data import input_data, weights_data

inputs = np.array([[[1, 0, 1, 2, 1], [0, 2, 1, 0, 1], [1, 1, 0, 2, 0], [2, 2, 1, 1, 0], [2, 0, 1, 2, 0]],
                   [[2, 0, 2, 1, 1], [0, 1, 0, 0, 2], [1, 0, 0, 2, 1], [1, 1, 2, 1, 0], [1, 0, 1, 1, 1]]],
                  dtype=np.float32)
weights = np.array([[[1, 0, 1], [-1, 1, 0], [0, -1, 0]], [[-1, 0, 1], [0, 0, 1], [1, 1, 1]]], dtype=np.float32)
inputs = np.float64(input_data)
weights = np.float64(weights_data)
print('inputs', inputs.shape, inputs.dtype)
print('weights', weights.shape, weights.dtype)


def devideInt(val):
    val = int(val)
    if val % 2 == 0:
        return val // 2, val // 2
    else:
        return val // 2, val // 2 + 1


def convolution(inputs, kernel):
    H, W = inputs.shape[:2]
    KH, KW = kernel.shape[:2]
    PH, PW = KH - 1, KW - 1
    PH1, PH2 = devideInt(PH)
    PW1, PW2 = devideInt(PW)
    padded = np.zeros((H + PH, W + PW), dtype=np.float64)
    padded[PH1:H + PH1, PW1:W + PW1] = inputs
    result = np.zeros_like(inputs, dtype=np.float64)
    for row in range(PH1, H + PH1):
        for col in range(PW1, W + PW1):
            roi = padded[row-PH1:row+PH1+1, col-PW1:col+PW1+1]
            # roi *= kernel  # ATTENTION Cannot in-place!
            result[row-PH1, col-PW1] = (roi * kernel).sum()
    return result


def my_depthwise(inputs, weights):
    result = []
    for i, ch in enumerate(inputs):
        kernel = weights[i]
        result.append(convolution(ch, kernel))
    return np.float64(result)

def main():
    results = my_depthwise(inputs, weights)
    print(results)


# ⑤	打印输出深度可分离卷积结果
if '__main__' == __name__:
    main()